package com.sensePlusVR.realGame;

import android.annotation.SuppressLint;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;

import java.util.HashMap;

@SuppressLint("NewApi")
public class SoundPlayer {
	private SoundPool mSoundPool;
	private final int maxStreams = 1;
	//private List<Integer> SoundIds;
	private HashMap<Integer, Integer> mSoundIds = new HashMap<Integer, Integer>();
	
	public SoundPlayer(){
        //当前系统的SDK版本大于等于21(Android 5.0)时  
        if (Build.VERSION.SDK_INT >= 21) {  
            SoundPool.Builder builder = new SoundPool.Builder();  
            //传入音频数量  
            builder.setMaxStreams(maxStreams);  
            //AudioAttributes是一个封装音频各种属性的方法  
            AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();  
            //设置音频流的合适的属性  
            attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);  
            //加载一个AudioAttributes  
            builder.setAudioAttributes(attrBuilder.build());  
            mSoundPool = builder.build();  
        }  
        //当系统的SDK版本小于21时  
        else {//设置最多可容纳2个音频流，音频的品质为5  
            mSoundPool = new SoundPool(2, AudioManager.STREAM_SYSTEM, maxStreams);  
        }
	}
	
//	public void setSoundFiles(List<String> files){
//		for (String s:files){
//			int Id = mSoundPool.load(s, 1);
//			SoundIds.add(Id);
//		}
//	}
	
	public void loadSoundFile(int index, String file){
		int Id = mSoundPool.load(file, 1);
		mSoundIds.put(index, Id);
	}
	
	public void releaseSoundFiles(){
		//SoundIds.clear();
		for (Integer key:mSoundIds.keySet()){
			Integer soundID = mSoundIds.get(key);
			if (soundID != null){
				mSoundPool.unload(soundID);
			}
		}
		mSoundIds.clear();
		//mSoundPool.release();
	}
	

	public void play(int index, float volume){
		Integer Id = mSoundIds.get(index);
		if (Id == null){
			return;
		}
		mSoundPool.play(Id, volume, volume, 1, 0, 1.0f);
	}
	

	public void stop(int index){
		Integer streamID = mSoundIds.get(index);
		if (streamID != null)
			mSoundPool.stop(streamID);
	}
	
	public void playRepeat(int index, float volume){
		Integer Id = mSoundIds.get(index);
		if (Id == null){
			return;
		}
		mSoundPool.play(Id, volume, volume, 1, -1, 1.0f);
	}
}
